package org.lookouster.nextAgadir.pointageBureau.ui;

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

import org.lookouster.nextAgadir.pointageBureau.bases.Employe;
import org.lookouster.nextAgadir.pointageBureau.outils.BDFunctions;
import org.lookouster.nextAgadir.pointageBureau.outils.Commons;
import org.lookouster.nextAgadir.pointageBureau.outils.functions;

/*
 * SearchEmp.java
 *
 * Created on 28 avril 2008, 22:25
 */



/**
 *
 * @author  Lookouster
 */
public class SearchEmp extends javax.swing.JDialog {
    
    /** Creates new form SearchEmp */
	Frame parent;
    public SearchEmp(java.awt.Frame p) {
        super(p, false);
        parent=p;
        
        try {
			UIManager.setLookAndFeel( 
					UIManager.getSystemLookAndFeelClassName() );
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
			try {
				initComponents();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     * @throws Exception 
     * @throws Exception 
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() throws Exception  {

        txtMat = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txtNom = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtCIN = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        b_ok = new javax.swing.JButton();
        b_details= new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jComboBox1 = new javax.swing.JComboBox();
        qualifBox=new javax.swing.JComboBox();
        b_edit=new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

       
        
        

        jLabel1.setText(UICommons.fSearchMat);
        

        jLabel2.setText(UICommons.fSearchNom);
        

       

        jLabel3.setText(UICommons.fSearchCIN);
        


        jLabel4.setText(UICommons.fSearchNotif); 
        

        jLabel5.setText(UICommons.fSearchTitle);
        jLabel6.setText(UICommons.fSearchType);
        jLabel7.setText(UICommons.fSearchQual);
        

        b_ok.setText(UICommons.btnValid);
        
        b_edit.setText(UICommons.btnEdit);
        
        b_edit.setEnabled(false);
        
        b_details.setEnabled(false);
        
        b_details.setText(UICommons.btnDet);
        
        b_ok.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				try {
					searchEmp();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
        	
        	
        });
        
        b_edit.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				try {
					editEmp();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
        	
        	
        });
        
        b_details.addActionListener(new ActionListener()
        {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				showDetails();
			}
        	
        });
        
        
        

     

        jTable1.setSelectionMode(0);
        
        jScrollPane1.setViewportView(jTable1);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] 
                      { UICommons.fSearchOuvr,UICommons.fSearchCtl,
        		UICommons.fSearchBoth}));
        jComboBox1.setSelectedIndex(2);
        jComboBox1.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				listenToChoice();
			}
        	
        });
        String [] tmp=BDFunctions.getQualificationsArray();
        int size=0;
        if(tmp!=null)
        	size=tmp.length;
        String[] qual=new String[size+1];
        for(int i=0;i<size;i++)
        	qual[i]=tmp[i];
        qual[size]="Tous";
        qualifBox.setModel(new javax.swing.DefaultComboBoxModel(
        		qual));
        qualifBox.setSelectedIndex(size);
        
        qualifBox.setVisible(false);
        jLabel7.setVisible(false);
        
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jLabel5))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGap(8, 8, 8)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtMat, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(54, 54, 54)
                                .addComponent(jLabel2)
                                .addGap(8, 8, 8)
                                .addComponent(txtNom, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(54, 54, 54)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtCIN, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel4)
                                .addGap(54, 54, 54)
                                .addComponent(jLabel6)
                                .addGap(8, 8, 8)
                                .addComponent(jComboBox1)
                                .addGap(54, 54, 54)
                                .addComponent(jLabel7)
                                .addGap(8, 8, 8)
                                .addComponent(qualifBox)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                //.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                
                                
                                .addComponent(b_ok)
                                .addGap(8, 8, 8)
                                .addComponent(b_edit)
                                .addGap(8, 8, 8)
                                .addComponent(b_details))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(98, 98, 98)
                                //.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                                )))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 583, Short.MAX_VALUE)
                        /*.addGap(30, 30, 30)*/))
                .addContainerGap()
                .addGap(50, 50, 50))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel6)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                .addComponent(jLabel7)
	                .addComponent(qualifBox))
               .addGap(28, 28, 28)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtCIN, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(b_ok)
                    .addComponent(b_edit)
                    .addComponent(b_details)
                    .addComponent(jLabel2)
                    .addComponent(txtNom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtMat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(28, 28, 28)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(17, Short.MAX_VALUE))
        );

        pack();
    }


    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                SearchEmp dialog = new SearchEmp(new javax.swing.JFrame());
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    
    public void searchEmp() throws Exception
    {
    	String mat=null, nom=null, cin=null,qualification=null;
    	boolean bqual=false;
    	if(jComboBox1.getSelectedIndex()==0)
    	{
    		qualification=qualifBox.getSelectedItem().toString();
    		if(qualification.equalsIgnoreCase("Tous"))
    		{
    			bqual=false;
    		}
    		else
    			bqual=true;
    	}
    	if(txtMat.getText().trim().length()!=0)
    	{
    		mat=txtMat.getText().trim();
    		
    	}
    	if(txtNom.getText().trim().length()!=0)
    	{
    		nom=txtNom.getText().trim();
    		
    	}
    	if(txtCIN.getText().trim().length()!=0)
    	{
    		cin=txtCIN.getText().trim();
    		
    	}
    	if(!bqual)
    	{
    		if((mat!=null) || (nom!=null) || (cin!=null))
    		{
    			int type;
    			if(jComboBox1.getSelectedIndex()==0)
    				type=Commons.DB_TYP_OUVR;
    			else if(jComboBox1.getSelectedIndex()==1)
    				type=Commons.DB_TYP_CTL;
    			else
    				type=0;
    			List<EmployeTable> results=BDFunctions.getEmps(mat,cin,nom,type);
    			if(results!=null)
    				jTable1.setModel(new EmpModel(results));
    			else
    			{
    				jTable1.setModel(new javax.swing.table.DefaultTableModel(
    			            new Object [][] {},
    			            UICommons.empTableFields) 
    					{
    			            boolean[] canEdit = new boolean [] {
    			                false, false, false, false
    			            };

    			            public boolean isCellEditable(int rowIndex, int columnIndex) {
    			                return canEdit [columnIndex];
    			            }
    			        });
    				JOptionPane.showMessageDialog(this,UICommons.notifNoResults);
    			}
    		}
    		else
    			JOptionPane.showMessageDialog(this,UICommons.notifFields);
    	}
    	else
    	{
    		List<OuvrierTable> results=BDFunctions.getOuvrs(mat,cin,nom,qualification);
    		if(results!=null)
				jTable1.setModel(new OuvrModel(results));
			else
			{
				jTable1.setModel(new javax.swing.table.DefaultTableModel(
			            new Object [][] {},
			            UICommons.ouvrTableFields) 
					{
			            boolean[] canEdit = new boolean [] {
			                false, false, false, false
			            };

			            public boolean isCellEditable(int rowIndex, int columnIndex) {
			                return canEdit [columnIndex];
			            }
			        });
				JOptionPane.showMessageDialog(this,UICommons.notifNoResults);
			}
    	}
    		jTable1.getSelectionModel().addListSelectionListener(
    				new ListSelectionListener(){

						@Override
						public void valueChanged(ListSelectionEvent arg0) {
							// TODO Auto-generated method stub
						actOnButtons(arg0);
						//functions.affiche("Table selection changed");


						}
    			
    		});
    }
    
    
    /**
     * Handle Selection model for the jTable1 widget
     * @param arg0
     */
    public void actOnButtons(ListSelectionEvent arg0)
    {
    	ListSelectionModel lsm = (ListSelectionModel)arg0.getSource();
		if(!lsm.isSelectionEmpty() && jTable1.getValueAt(jTable1.getSelectedRow(),
				5).toString().equalsIgnoreCase(UICommons.statusOk))
		{
			b_edit.setEnabled(true);
			b_details.setEnabled(true);
		}
		else
		{
			b_edit.setEnabled(false);
			b_details.setEnabled(false);
		}
    }
    
    public void listenToChoice()
    {
    	
    	if(jComboBox1.getSelectedIndex()==0)
    	{
    		qualifBox.setVisible(true);
    		jLabel7.setVisible(true);
    	}
    	else
    	{
    		qualifBox.setVisible(false);
    		jLabel7.setVisible(false);
    	}
    		
    }
    
    class EmpModel implements TableModel{
    	
    	List<EmployeTable> results;
    	
    	public EmpModel(List<EmployeTable> rs)
    	{
				results=rs;
    	}
		@Override
		public void addTableModelListener(TableModelListener arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public Class<?> getColumnClass(int arg0) {
			 return getValueAt(0, arg0).getClass();
		}

		@Override
		public int getColumnCount() {
			// TODO Auto-generated method stub
			return UICommons.empTableFields.length;
		}

		@Override
		public String getColumnName(int arg0) {
			// TODO Auto-generated method stub
			return UICommons.empTableFields[arg0];
		}

		@Override
		public int getRowCount() {
			// TODO Auto-generated method stub
			return results.size();
		}

		@Override
		public Object getValueAt(int arg0, int arg1) {
			// TODO Auto-generated method stub
			switch(arg1)
			{
			case 0:return results.get(arg0).getMatricule();
			case 1:return results.get(arg0).getCin();
			case 2:return results.get(arg0).getNom();
			case 3:return results.get(arg0).getPrenom();
			case 4:return results.get(arg0).getType();
			case 5:return results.get(arg0).getStatut();
			default:return null;
			}
		}

		@Override
		public boolean isCellEditable(int arg0, int arg1) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void removeTableModelListener(TableModelListener arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void setValueAt(Object arg0, int arg1, int arg2) {
			// TODO Auto-generated method stub
			
		}
    	
    }
    
    class OuvrModel implements TableModel
    {
    	
    	List<OuvrierTable> results;

    	
    	public OuvrModel(List<OuvrierTable> rs)
    	{
    		results=rs;
    	}
		@Override
		
		
		
		public void addTableModelListener(TableModelListener l) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public Class<?> getColumnClass(int columnIndex) {
			// TODO Auto-generated method stub
			return getValueAt(0, columnIndex).getClass();
		}

		@Override
		public int getColumnCount() {
			// TODO Auto-generated method stub
			return UICommons.ouvrTableFields.length;
		}

		@Override
		public String getColumnName(int columnIndex) {
			// TODO Auto-generated method stub
			return UICommons.ouvrTableFields[columnIndex];
		}

		@Override
		public int getRowCount() {
			// TODO Auto-generated method stub
			return results.size();
		}

		@Override
		public Object getValueAt(int arg0, int arg1) {
			// TODO Auto-generated method stub
			switch(arg1)
			{
			case 0:return results.get(arg0).getMatricule();
			case 1:return results.get(arg0).getCin();
			case 2:return results.get(arg0).getNom();
			case 3:return results.get(arg0).getPrenom();
			case 4:return results.get(arg0).getType();
			case 5:return results.get(arg0).getStatut();
			case 6:return results.get(arg0).getQualification();
			default:return null;
			}
		}

		@Override
		public boolean isCellEditable(int rowIndex, int columnIndex) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void removeTableModelListener(TableModelListener l) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void setValueAt(Object value, int rowIndex, int columnIndex) {
			// TODO Auto-generated method stub
			
		}
    	
    }
    
    public void editEmp()
    {
    	if(jTable1.getSelectedRowCount()==1)
    	{
    		JDialog empBox;
    		String matricule=jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString();
    		//System.out.println("mat= "+matricule);
    		empBox = new NewEmployee(parent,4,matricule);
            empBox.setLocationRelativeTo(this);
            empBox.setVisible(true);
    	}
    	else
    		JOptionPane.showMessageDialog(this,UICommons.notifSelRow);
    }
    
    
    /**
     * Launch Employee Details box after a click on the b_edit button
     */
    public void showDetails()
    {
    	if(jTable1.getSelectedRowCount()==1)
    	{
    		 NewEmployee empBox=new NewEmployee(parent,3,
    				 jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString());
    		 empBox.setVisible(true);
    		 empBox.setLocationRelativeTo(this);
    		 
    	}
    	else
    		JOptionPane.showMessageDialog(this,UICommons.notifSelRow);
    }
    
    
    
    
    
    
    
    // Variables declaration - do not modify
    private javax.swing.JButton b_ok,b_edit,b_details;
    private javax.swing.JComboBox jComboBox1;//Type box
    private javax.swing.JComboBox qualifBox;//Qualifications combo box
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;//Titre page
    private javax.swing.JLabel jLabel6;//Type
    private javax.swing.JLabel jLabel7;//Qualification
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField txtMat;
    private javax.swing.JTextField txtNom;
    private javax.swing.JTextField txtCIN;
    
   
    // End of variables declaration
    
}
